var express = require('express');
var async = require('async');
var router = express.Router();
var	mongoose = require('mongoose'),
	memberUsers = mongoose.model('member_users'),
	messageLists = mongoose.model('message_lists'),
	teamLists = mongoose.model('team_teamLists');

/* 获取团队信息 */
router.post('/teamInfo', (req, res, next) => {
	let params = req.body;

	teamLists.find({
		teamId: params.teamId
	}, (err, data) => {
		if(err){
			res.json({
				error: '查询团队失败'
			})
		}else{
			res.json(data[0]);
		}
	})
})

//修改团队信息 - jobList
router.post('/updateTeamInfo', (req, res, next) => {
	let params = req.body;

	teamLists.update({
		teamId: params.teamId
	}, {
		$set: {
			jobList: params.jobList
		}
	}).exec(err => {
		if(err){
			res.json({
				error: '修改团队信息出错！'
			})
		}else{
			res.end();
		}
	})
})

/* 创建团队. */
router.post('/createTeam', function(req, res, next) {
	let params = req.body;

	teamLists.find({
		teamName: params.teamName
	}, (err, data) => {
		if(err){
			res.json({
				error: '查询团队失败'
			})
		}else{
			if(data.length){
				res.json({
					error: '已有同名团队，请修改名称'
				})
			}else{
				let teamId = new Date().getTime() + '',
					teamSave = new teamLists({
						teamName: params.teamName,
						teamId: teamId,
						founder: params.mobile
					});

				//更新用户信息
				memberUsers.update({
					mobile: params.mobile
				}, {
					$set: {
						teamId: teamId,
						teamName: params.teamName,
						level: 1
					}
				}).exec(err => {
					if(err){
						res.json({
							error: '更新用户信息'
						})
					}else{
						//保存团队信息
						teamSave.save(err => {
							if(err){
								res.json({
									error: '创建团队出错'
								})
							}else{
								res.json({
									teamName: params.teamName,
									teamId: teamId
								})
							}
						})
					}
				})
			}
		}
	})
});

// 邀请新成员
router.post('/addNewMember', (req, res, next) => {
	let params = req.body,
		datas = [];

	async.series([
		//查询用户信息
		callback => {
			memberUsers.find({
				mobile: params.mobile
			}, (err, data) => {
				if(err){
					res.json({
						error: '查询用户是否有团队失败！'
					})
				}else{
					if(!data.length){ //用户不存在
						res.json({
							error: '查无此人！'
						})
					}else if(data[0].teamId){ //已有团队
						res.json({
							error: '对方已有团队，无法邀请！'
						})
					}else{ //正常
						datas = data[0];
						callback()
					}
				}
			})
		},
		//发送消息
		callback => {
			let saveMsg = new messageLists({
				mobile: datas.mobile,
				userName: datas.userName,
				sendMobile: params.sendMobile,
				sendUserName: params.sendUserName,
				message: params.message,
				msgId: new Date().getTime() + '',
				status: 0
			});

			saveMsg.save(err => {
				if(err){
					res.json({
						error: '发送消息出错！'
					})
				}else{
					res.end()
				}
			})
		}
	])
})

module.exports = router;